# coding=utf-8
import baostock as bs
import datetime
import pandas as pd


def saveDB(data):

    print(data[0])

    return data


# nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
nowTime = datetime.datetime.now().strftime('%Y-%m-%d')
# 50天前
lastTime = (datetime.datetime.now() - datetime.timedelta(days=50)).strftime('%Y-%m-%d')

lg = bs.login()
print('login respond error_code:' + lg.error_code)
print('login respond  error_msg:' + lg.error_msg)

#### 获取历史K线数据 ####
# 详细指标参数，参见“历史行情指标参数”章节
rs = bs.query_history_k_data_plus("sh.601985",
                                  "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                                  start_date=lastTime, end_date=nowTime,
                                  frequency="d", adjustflag="3")  # frequency="d"取日k线，adjustflag="3"默认不复权
print('query_history_k_data_plus respond error_code:' + rs.error_code)
print('query_history_k_data_plus respond  error_msg:' + rs.error_msg)

#### 打印结果集 ####
data_list = []
while (rs.error_code == '0') & rs.next():
    # 获取一条记录，将记录合并在一起
    saveDB(rs.get_row_data())
    # data_list.append(rs.get_row_data())


# result = pd.DataFrame(data_list, columns=rs.fields)
# #### 结果集输出到csv文件 ####
# result.to_csv("./data/history_k_data.csv", encoding="gbk", index=False)
# print(result)

#### 登出系统 ####
bs.logout()
